package org.cid54.jshopper.dao.impl;

import java.util.List;
import org.cid54.jshopper.dao.UserDao;
import org.cid54.jshopper.model.User;
import org.cid54.jshopper.model.UserGroup;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 *
 * @author fgo
 */
@Repository
public class UserDaoImpl extends SuperEntityDaoImpl<User> implements UserDao {

    @Override
    protected Class getEntityClass() {
        return User.class;
    }

    @Override
    public User findByName(String name) {
        Criteria criteria = this.getNewCriteria();

        criteria.add(Restrictions.eq("name", name));

        criteria.setFetchMode("userGroups", FetchMode.JOIN);

        return (User) criteria.uniqueResult();
    }

    @Override
    public List<User> findByUserGroup(UserGroup userGroup) {
        Criteria criteria = this.getNewCriteria();

        criteria.add(Restrictions.eq("userGroup", userGroup));

        return criteria.list();
    }

    @Override
    public List<User> getAll() {
        Criteria criteria = this.getNewCriteria();

        if (this.isSortableByName()) {
            criteria.addOrder(Order.asc("name"));
        }

        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        return criteria.list();
    }

    @Override
    protected boolean isSortableByName() {
        return true;
    }

    @Override
    public User findByGuid(String guid) {

        Criteria criteria = this.getNewCriteria();

        criteria.add(Restrictions.eq("guid", guid));

        return (User) criteria.uniqueResult();

    }
}
